import pyautogui
import time
from PIL import Image
import pytesseract
import difflib
import os
import ctypes
import win32api


class Util:
    @staticmethod
    def repeat_click(x=0, y=0, time_delay=1):
        while True:
            pyautogui.doubleClick(x, y)
            time.sleep(time_delay)

    @staticmethod
    def get_screenshot(region=None, sub_folder=""):
        img = pyautogui.screenshot(region=region)
        # if sub_folder != "":
        #     sub_folder = "/" + sub_folder
        # path = f'./images{sub_folder}/img_{time.strftime("%m-%d-%H-%M-%S", time.localtime())}.jpg'
        # img.save(path)
        return img


    @staticmethod
    def get_text_from_img(img):
        # 获取截图问题，并存储
        # img = Image.open(img_path)
        text = pytesseract.image_to_string(img, lang='chi_sim')
        return text.replace('\n', '').strip()

    @staticmethod
    def string_similar(s1, s2):
        return difflib.SequenceMatcher(None, s1, s2).quick_ratio()

    @staticmethod
    def print_cursor_position():
        while True:
            x, y = pyautogui.position()
            pos_str = "Position:" + str(x).rjust(4) + ',' + str(y).rjust(4)
            print(pos_str)
            time.sleep(0.2)
            os.system('cls')

    @staticmethod
    def click(x, y, delay=0):
        if delay == 0:
            pyautogui.click(x, y)
        elif delay < 0:
            time.sleep(-1 * delay)
            pyautogui.click(x, y)
        else:
            pyautogui.click(x, y)
            time.sleep(delay)

    @staticmethod
    def move(x, y):
        ctypes.windll.user32.SetCursorPos(x, y)

    @staticmethod
    def press(x, y, button=1):
        buttionAction = 2 ** ((2 * button) - 1)
        win32api.mouse_event(buttionAction, x, y)

    @staticmethod
    def release(x, y, button=1):
        buttionAction = 2 ** (2 * button)
        win32api.mouse_event(buttionAction, x, y)

    @staticmethod
    def click_s(x, y, time_period=0.2):
        Util.move(x, y)
        time.sleep(1)
        Util.press(x, y)
        time.sleep(time_period)
        Util.release(x, y)
        time.sleep(1)


if __name__ == '__main__':
    img = pyautogui.screenshot(region=[160, 1605, 435, 70])
    text = pytesseract.image_to_string(img, lang='chi_sim')
    print(text)
